package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.adminUserLoginMapper;
import com.heima.admin.service.adminUserLoginService;
import com.heima.model.apuser.dtos.AdUserDto;
import com.heima.model.apuser.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author rookie001
 * @creat 2023-06-19-9:45
 */
@Service
public class adminUserLoginServiceImpl extends ServiceImpl<adminUserLoginMapper, AdUser> implements adminUserLoginService {

    //登录
    @Override
    public ResponseResult login(AdUserDto dto) {
        //数据校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询ad_user
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        //若为空 不存在该用户
        if (adUser == null || !adUser.getName().equals(dto.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户不存在");
        }
        //不为空 加密盐和密码 和ad_user密码比对
        String pw = DigestUtils.md5DigestAsHex((dto.getPassword()+ adUser.getSalt()+"").getBytes());
        if (!pw.equals(adUser.getPassword())) {
            //比对失败 返回密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }
        //比对成功 修改最后一次登录时间 更新ad_user
        adUser.setLoginTime(new Date());
        updateById(adUser);


        // 获取token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        //防止密码泄露
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);
        map.put("token", token);

        return ResponseResult.okResult(map);
    }
}
